package com.huitone.smspfm.oldclient.model;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.bin.common.utils.DateTimeUtils;
import com.bin.common.utils.StringUtils;
import com.huitone.smspfm.oldclient.dao.entity.SmsSend;

public class MtSms extends AbstractSms {
	
	private static final long serialVersionUID = 1L;
	
	//private final static ExtLogger logger = ExtLogger.create(MtSms.class);

	//public static List<MtSms> store = new ArrayList<>();
	
	private String content;
	
	private String mesgtype;
	
	private String srr;
	
	private String crttime;
	
	private int splitCount; // <1>
	
	private int splitIndex; // <2>
	
	private int smscode; // <4>
	
	private String oldserialnos;
	
	// ----------------------------
	
	private long coderule; // 前部分的编码规则
	
	private long datetime; // 中间的时间
	
	private long seqnumber; // 末尾的序号
	
	private int reportflag;
	
	private String srvNode;
	
	private String serviceCode;
	
	private Date lastSendTime;
	
	private int iSendTimes;
	
	private Date readTime;
	
	public static Map<String, MtGroup> parse(StringBuffer buffer) {
		Map<String, MtGroup> result = new HashMap<>();
        if (buffer != null) {
    		Pattern p = Pattern.compile(".*?<endl/>");
            Matcher m = p.matcher(buffer);
            while(m.find()) {
            	String res = m.group();
            	MtSms mtSms = build(res);
            	if (!StringUtils.isEmpty(mtSms.getSerialno())) {
            		String groupKey = null;
        			int count = mtSms.getSplitCount();
            		if(count > 0) { // 长短信
            			// 长短信根据客户端名/手机号码/发送端口号/短信编码/短信分割条数进行分组
            			StringBuffer keyBuffer = new StringBuffer();
            			keyBuffer.append(mtSms.getClientname());
            			keyBuffer.append(mtSms.getMobileno());
            			keyBuffer.append(mtSms.getSendport());
            			keyBuffer.append(mtSms.getSmscode());
            			groupKey = keyBuffer.toString();
            		} else {
            			groupKey = mtSms.getSerialno();
            		}
        			if (result.containsKey(groupKey)) {
        				result.get(groupKey).addItem(mtSms);
        			} else {
        				MtGroup group = new MtGroup();
        				group.setGroupKey(groupKey);
        				group.setCount(count);
        				group.addItem(mtSms);
        				result.put(groupKey, group);
        			}
            	}
            }
        }
        return result;
	}
	
	
	public static  Map<String, MtGroup> parse(List<SmsSend> smsSends) {
		Map<String, MtGroup> result = new HashMap<>();
		for(SmsSend smsSend:smsSends){
        	MtSms mtSms = smsSend.build();
        	if (!StringUtils.isEmpty(mtSms.getSerialno())) {
        		String groupKey = null;
    			int count = mtSms.getSplitCount();
        		if(count > 0) { // 长短信
        			// 长短信根据客户端名/手机号码/发送端口号/短信编码/短信分割条数进行分组
        			StringBuffer keyBuffer = new StringBuffer();
        			keyBuffer.append(mtSms.getClientname());
        			keyBuffer.append(mtSms.getMobileno());
        			keyBuffer.append(mtSms.getSendport());
        			keyBuffer.append(mtSms.getSmscode());
        			groupKey = keyBuffer.toString();
        		} else {
        			groupKey = mtSms.getSerialno();
        		}
    			if (result.containsKey(groupKey)) {
    				result.get(groupKey).addItem(mtSms);
    			} else {
    				MtGroup group = new MtGroup();
    				group.setGroupKey(groupKey);
    				group.setCount(count);
    				group.addItem(mtSms);
    				result.put(groupKey, group);
    			}
        	}
		}
		return result;
	}
	
	
	private static MtSms build(String input) {

		MtSms mTSms = new MtSms();

        Matcher serialnoM = Pattern.compile("<serialno>(.*)</serialno>").matcher(input);
        while(serialnoM.find()) {
                mTSms.setSerialno(serialnoM.group(1));
        }
        
        Matcher clientnameM = Pattern.compile("<clientname>(.*)</clientname>").matcher(input);
        while(clientnameM.find()) {
                mTSms.setClientname(clientnameM.group(1));
        }

        Matcher sendportM = Pattern.compile("<sendport>(.*)</sendport>").matcher(input);
        while(sendportM.find()) {
                mTSms.setSendport(sendportM.group(1));
        }

        Matcher mobilenoM = Pattern.compile("<mobileno>(.*)</mobileno>").matcher(input);
        while(mobilenoM.find()) {
                mTSms.setMobileno(mobilenoM.group(1));
        }

        Matcher contentM = Pattern.compile("<content>(.*)</content>").matcher(input);
        while(contentM.find()) {
                mTSms.setContent(contentM.group(1));
        }

        Matcher mesgtypeM = Pattern.compile("<mesgtype>(.*)</mesgtype>").matcher(input);
        while(mesgtypeM.find()) {
                mTSms.setMesgtype(mesgtypeM.group(1));
        }

        Matcher srrM = Pattern.compile("<srr>(.*)</srr>").matcher(input);
        while(srrM.find()) {
                mTSms.setSrr(srrM.group(1));
        }
        
        Matcher crttimeM = Pattern.compile("<crttime>(.*)</crttime>").matcher(input);
        while(crttimeM.find()) {
                mTSms.setCrttime(crttimeM.group(1));
        }
        
        String content = mTSms.getContent();
        
        if (StringUtils.getMatchCount(content, "<1>.*?</1>") > 0) {
        	
        	Matcher splitCountM = Pattern.compile("<1>(.*)</1>").matcher(content);
            while(splitCountM.find()) {
                    mTSms.setSplitCount(StringUtils.toIntegerP(splitCountM.group(1)));
            }
            
            Matcher splitIndexM = Pattern.compile("<2>(.*)</2>").matcher(content);
            while(splitIndexM.find()) {
                    mTSms.setSplitIndex(StringUtils.toIntegerP(splitIndexM.group(1)));
            }
            
            Matcher splitContentM = Pattern.compile("<3>(.*)</3>").matcher(content);
            while(splitContentM.find()) {
                    mTSms.setContent(splitContentM.group(1));
            }
            
            Matcher smscodeM = Pattern.compile("<4>(.*)</4>").matcher(content);
            while(smscodeM.find()) {
                    mTSms.setSmscode(StringUtils.toIntegerP(smscodeM.group(1)));
            }
        }
        
        mTSms.setReadTime(new Date());
        
        /**
         * @desc 对于旧短信平台: 
         *     短信唯一的顺序号，不超过50位，是本表的主键，生成规则如下：客户帐号+ 2位通道代码+2位业务代码+YYYYMMDDHHMISS（14位）+顺序号（n位）
         * 
         * @todo 提取两位业务代码
         */
        int length = StringUtils.length(mTSms.getClientname()); 
        int start = length + 2; 
        int end = start + 2;
        mTSms.setServiceCode(StringUtils.substring(mTSms.getSerialno(), start, end));
        
        return mTSms;
	}
	
	public static MtSms build(List<Object> list) {
		
		MtSms mtSms = new MtSms();
		
		mtSms.setSerialno(StringUtils.toString(list.get(0)));
		mtSms.setClientname(StringUtils.toString(list.get(1)));
		mtSms.setSendport(StringUtils.toString(list.get(2)));
		mtSms.setMobileno(StringUtils.toString(list.get(3)));
		mtSms.setContent(StringUtils.toString(list.get(4)));
		mtSms.setMesgtype(StringUtils.toString(list.get(5)));
		mtSms.setSrr(StringUtils.toString(list.get(6)));
		mtSms.setSplitCount(StringUtils.toInteger(list.get(7)));
		mtSms.setSmscode(StringUtils.toInteger(list.get(8)));
		mtSms.setOldserialnos(StringUtils.toString(list.get(9)));
		mtSms.setCoderule(StringUtils.toLong(list.get(10)));
		mtSms.setDatetime(StringUtils.toLong(list.get(11)));
		mtSms.setSeqnumber(StringUtils.toLong(list.get(12)));
		mtSms.setSrvNode(StringUtils.toString(list.get(13)));
		mtSms.setServiceCode(StringUtils.toString(list.get(14)));
		mtSms.setReportflag(StringUtils.toInteger(list.get(15)));
		try {
			mtSms.setLastSendTime(DateTimeUtils.strToDate(StringUtils.toString(list.get(16)), "yyyyMMddHHmmss"));
		} catch (Exception e) {
			mtSms.setLastSendTime(null);
		}
		
		mtSms.setiSendTimes(StringUtils.toInteger(list.get(17)));
		
		return mtSms;
	}
	
	public static List<Object> getColumns() {
		List<Object> list = new ArrayList<>();
		
		list.add("serialno");
		list.add("clientname");
		list.add("sendport");
		list.add("mobileno");
		list.add("content");
		list.add("mesgtype");
		list.add("srr");
		list.add("splitCount");
		list.add("smscode");
		list.add("oldserialnos");
		list.add("coderule");
		list.add("datetime");
		list.add("seqnumber");
		list.add("srvNode");
		list.add("serviceCode");
		list.add("reportflag");
		list.add("lastSendTime");
		list.add("iSendTimes");
		
		return list;
	}
	
	public Map<Object, Object> getMap() {
		Map<Object, Object> map = new HashMap<>();
		
		map.put("serialno", StringUtils.toString(serialno));
		map.put("clientname", StringUtils.toString(clientname));
		map.put("sendport", StringUtils.toString(sendport));
		map.put("mobileno", StringUtils.toString(mobileno));
		map.put("content", StringUtils.toString(content));
		map.put("mesgtype", StringUtils.toString(mesgtype));
		map.put("srr", StringUtils.toString(srr));
		map.put("splitCount", StringUtils.toString(splitCount));
		map.put("smscode", StringUtils.toString(smscode));
		map.put("oldserialnos", StringUtils.toString(oldserialnos));
		
		map.put("coderule", StringUtils.toString(serviceCode));
		map.put("datetime", StringUtils.toString(datetime));
		map.put("seqnumber", StringUtils.toString(seqnumber));
		map.put("srvNode", StringUtils.toString(srvNode));
		map.put("serviceCode", StringUtils.toString(serviceCode));
		map.put("reportflag", StringUtils.toString(reportflag));
		map.put("lastSendTime", DateTimeUtils.dateToStr(lastSendTime, "yyyyMMddHHmmss"));
		map.put("iSendTimes", StringUtils.toString(iSendTimes));
		
		return map;
	}
	
	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getMesgtype() {
		return mesgtype;
	}

	public void setMesgtype(String mesgtype) {
		this.mesgtype = mesgtype;
	}

	public String getSrr() {
		return srr;
	}

	public void setSrr(String srr) {
		this.srr = srr;
	}

	public String getCrttime() {
		return crttime;
	}

	public void setCrttime(String crttime) {
		this.crttime = crttime;
	}

	public int getSplitCount() {
		return splitCount;
	}

	public void setSplitCount(int splitCount) {
		this.splitCount = splitCount;
	}

	public int getSmscode() {
		return smscode;
	}

	public void setSmscode(int smscode) {
		this.smscode = smscode;
	}

	public int getSplitIndex() {
		return splitIndex;
	}

	public void setSplitIndex(int splitIndex) {
		this.splitIndex = splitIndex;
	}

	@Override
	public String toString() {
		return "MtSms [content=" + content + ", mesgtype=" + mesgtype + ", srr=" + srr + ", crttime=" + crttime
		        + ", splitCount=" + splitCount + ", splitIndex=" + splitIndex + ", smscode=" + smscode
		        + ", oldserialnos=" + oldserialnos + ", coderule=" + coderule + ", datetime=" + datetime
		        + ", seqnumber=" + seqnumber + ", reportflag=" + reportflag + ", srvNode=" + srvNode + ", serviceCode="
		        + serviceCode + ", lastSendTime=" + lastSendTime + ", iSendTimes=" + iSendTimes + ", readTime="
		        + readTime + ", serialno=" + serialno + ", clientname=" + clientname + ", sendport=" + sendport
		        + ", mobileno=" + mobileno + "]";
	}
	
	public String buildRow() {
		
		StringBuffer buffer = new StringBuffer();
		
		buffer.append("<serialno>" + serialno + "</serialno>");
		buffer.append("<clientname>" + clientname + "</clientname>");
		buffer.append("<sendport>" + sendport + "</sendport>");
		buffer.append("<mobileno>" + mobileno + "</mobileno>");
		buffer.append("<content>" + content + "</content>");
		buffer.append("<mesgtype>" + mesgtype + "</mesgtype>");
		buffer.append("<srr>" + srr + "</srr>");
		buffer.append("<crttime>" + crttime + "</crttime>");
		buffer.append("<oldserialnos>" + oldserialnos + "</oldserialnos>");
		buffer.append("<lastsendtime>" + DateTimeUtils.dateToStr2(lastSendTime) + "</lastsendtime>");
		buffer.append("<sendtimes>" + iSendTimes + "</sendtimes>");
		buffer.append("<endl/>");
		
		return buffer.toString();
	}


	public String getOldserialnos() {
		return oldserialnos;
	}


	public void setOldserialnos(String oldserialnos) {
		this.oldserialnos = oldserialnos;
	}

	public String getSrvNode() {
		return srvNode;
	}

	public void setSrvNode(String srvNode) {
		this.srvNode = srvNode;
	}

	public String getServiceCode() {
		return serviceCode;
	}

	public void setServiceCode(String serviceCode) {
		this.serviceCode = serviceCode;
	}

	public long getCoderule() {
		return coderule;
	}

	public void setCoderule(long coderule) {
		this.coderule = coderule;
	}

	public long getDatetime() {
		return datetime;
	}

	public void setDatetime(long datetime) {
		this.datetime = datetime;
	}

	public long getSeqnumber() {
		return seqnumber;
	}

	public void setSeqnumber(long seqnumber) {
		this.seqnumber = seqnumber;
	}

	public int getReportflag() {
		return reportflag;
	}

	public void setReportflag(int reportflag) {
		this.reportflag = reportflag;
	}

	public int getiSendTimes() {
		return iSendTimes;
	}

	public void setiSendTimes(int iSendTimes) {
		this.iSendTimes = iSendTimes;
	}

	public Date getLastSendTime() {
		return lastSendTime;
	}

	public void setLastSendTime(Date lastSendTime) {
		this.lastSendTime = lastSendTime;
	}

	public Date getReadTime() {
		return readTime;
	}

	public void setReadTime(Date readTime) {
		this.readTime = readTime;
	}
	
	public boolean isLongSms() {
		return splitCount > 0;
	}
	
	public static void main(String[] args) {
		int length = StringUtils.length("S8812");
        int start = length + 2;
        int end = start + 2;
        String substring = StringUtils.substring("S881288XX2017060620055944872334", start, end);
        
        System.out.println(substring);
		
	}
}